<template>
  <div>
    <a-modal :width="300" v-model="showEditModal" title="重命名" @ok="onOk">
      <a-input class="" placeholder="组织名称" v-model.trim="newName"></a-input>
    </a-modal>
    <a-card size="small" :title="title">
      <div slot="extra">
        <a-dropdown>
          <a-menu slot="overlay" @click="handleMenuClick">
            <a-menu-item key="1"> <i class="fa fa-plus-circle mr5"/>新增一级组织 </a-menu-item>
            <a-menu-item key="2"> <i class="fa fa-upload mr5"/>导入组织数据 </a-menu-item>
            <a-menu-item key="3"> <i class="fa fa-user mr5"/>初始化分管领导 </a-menu-item>
          </a-menu>
          <a-button type="link"> <i class="fa fa-ellipsis-h"/> </a-button>
        </a-dropdown>
      </div>
      <div class="scroll" :style="{margin:'-10px', padding:'10px 10px 60px', height:`${winHeight-400}px`}">
        <a-tree
          v-if="showTree"
          class="draggable-tree"
          draggable
          :showLine="true"
          :showIcon="true"
          :loadData="onLoadData"
          :selectedKeys="selectedKeys"
          :defaultExpandedKeys="defaultExpandedKeys"
          :treeData="treeData"
          @select="onSelect"
          @drop="onDrop"
          @dragstart="()=>{return false}"
          ref="tree"
        >
          <template #title="{ key: treeKey, title, layer }">
            <a-dropdown :trigger="['contextmenu']">
              <span>{{ title }}</span>
              <template #overlay>
                <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey)">
                  <a-menu-item :key="0"><i class="fa fa-plus-circle mr5"/>新增</a-menu-item>
                  <a-menu-item :key="1" v-if="layer>1"><i class="fa fa-edit mr5"/>重命名</a-menu-item>
                  <a-menu-item :key="2" v-if="layer>1"><i class="fa fa-trash mr5"/>删除</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </a-tree>
      </div>
    </a-card>
  </div>
</template>

<script>
const loop = (data, key, callback) => {
  data.forEach((item, index, arr) => {
    if (item.key === key) {
      return callback(item, index, arr)
    }
    if (item.children) {
      return loop(item.children, key, callback)
    }
  })
}
export default {
  props: {
    title: {
      type: String,
      default: '组织架构管理'
    }
  },
  data () {
    return {
      showTree: false,
      showEditModal: false,
      currKey: '0',
      newName: '',
      selectedKeys: [],
      defaultExpandedKeys: [],
      treeData: [],
      nodeInfo: []
    }
  },
  mounted () {
    this.searchRoot()
  },
  methods: {
    generateTreeNode (data) {
      return {
        key: data.id,
        title: data.name,
        layer: data.layer
      }
    },
    getNodeFromTree (key) {
      let node
      loop([...this.treeData], key, (item) => {
        node = item
      })
      return node
    },
    searchRoot () {
      this.$http.post('/zg-system/org/root', {}, data => {
        const root = this.generateTreeNode(data)
        this.$http.get('/zg-system/org/next', { pid: root.key }, children => {
          root.disabled = true
          root.children = children.map(t => {
            return this.generateTreeNode(t)
          })

          this.treeData = [root]
          this.defaultExpandedKeys = [root.key]
          this.showTree = true
          if (root.children.length > 0) {
            this.selectedKeys = [root.children[0].key]
            this.$emit('nodeClick', root.children[0])
          }
        })
      })
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        this.$http.get('/zg-system/org/next', { pid: treeNode.dataRef.key }, data => {
          treeNode.dataRef.children = data.map(t => {
            return this.generateTreeNode(t)
          })
          this.treeData = [...this.treeData]
          resolve()
        })
      })
    },
    onSelect (selectedKeys, info) {
      this.selectedKeys = selectedKeys
      const node = info.node.dataRef
      this.$emit('nodeClick', node)
    },
    onDrop (info) {
      const dropKey = info.node.eventKey// 目标节点Key
      const dragKey = info.dragNode.eventKey// 拖拽节点Key
      const dropPos = info.node.pos.split('-')
      const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])// 位置前面、后面、里面
      console.log(info.node.dataRef.layer)
      if (info.node.dataRef.layer === 1 || info.dragNode.dataRef.layer === 1) {
        return false
      }
      this.$http.post('/zg-system/org/drop',
        {
          dragId: dragKey,
          dropId: dropKey,
          position: dropPosition
        }, () => {
          const data = [...this.treeData]
          let dragObj
          loop(data, dragKey, (item, index, arr) => {
            arr.splice(index, 1)
            dragObj = item
          })
          if (!info.dropToGap) {
            loop(data, dropKey, item => {
              item.children = item.children || []
              item.children.push(dragObj)
            })
          } else if (
            (info.node.children || []).length > 0 && // Has children
              info.node.expanded && // Is expanded
              dropPosition === 1 // On the bottom gap
          ) {
            loop(data, dropKey, item => {
              item.children = item.children || []
              item.children.unshift(dragObj)
            })
          } else {
            let ar
            let i
            loop(data, dropKey, (item, index, arr) => {
              ar = arr
              i = index
            })
            if (dropPosition === -1) {
              ar.splice(i, 0, dragObj)
            } else {
              ar.splice(i + 1, 0, dragObj)
            }
          }
          this.treeData = data
        })
    },
    onContextMenuClick (treeKey, menuKey) {
      if (menuKey === 0) {
        this.add(treeKey)
      } else if (menuKey === 1) {
        this.update(treeKey)
      } else if (menuKey === 2) {
        this.del(treeKey)
      }
    },
    add (key) {
      const node = this.getNodeFromTree(key)
      this.$http.post('/zg-system/org/add', node.key, data => {
        const result = {
          key: data.id,
          title: data.name
        }
        node.children = node.children || []
        node.children.push(result)
        this.treeData = [...this.treeData]
      })
    },
    update (key) {
      const node = this.getNodeFromTree(key)
      this.newName = node.title
      this.currKey = key
      this.showEditModal = true
    },
    del (key) {
      this.confirm(() => {
        this.$http.post('/zg-system/org/del', key, () => {
          loop([...this.treeData], key, (item, index, arr) => {
            arr.splice(index, 1)
          })
          this.treeData = [...this.treeData]
          this.$emit('update')
        })
      }, '确定要删除该组织么？')
    },
    onOk () {
      if (this.newName.length === 0) {
        this.$warning({ title: '请输入组织名称' })
        return
      }
      this.$http.post('/zg-system/org/update', { id: this.currKey, name: this.newName }, () => {
        const node = this.getNodeFromTree(this.currKey)
        node.title = this.newName
        this.$emit('update')
        this.showEditModal = false
      })
    },
    handleMenuClick () {}
  }
}
</script>
<style lang="less" scoped>
</style>
